package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        String data = StringUtils.join(dateList, ",");
        List<Double> turnovers = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",localDateTimeBegin);
            map.put("end",localDateTimeEnd);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null){
                turnover = 0.0;
            }
            turnovers.add(turnover);
        }
        String sumByData = StringUtils.join(turnovers, ",");
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .turnoverList(sumByData)
                .dateList(data)
                .build();
        return turnoverReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dataString = StringUtils.join(dateList, ",");
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        Map mapCount = new HashMap();
        Integer totalOrderCount = orderMapper.getCount(mapCount);
        mapCount.put("status",Orders.COMPLETED);
        Integer validOrderCount = orderMapper.getCount(mapCount);
        Double orderCompletionRate = ((double)validOrderCount/(double)totalOrderCount);
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",localDateTimeBegin);
            map.put("end",localDateTimeEnd);
            Integer orderCount = orderMapper.getCount(map);
            map.put("status", Orders.COMPLETED);
            Integer validOrder = orderMapper.getCount(map);
            orderCountList.add(orderCount);
            validOrderList.add(validOrder);
        }
        String orderCountString = StringUtils.join(orderCountList, ",");
        String validOrderString = StringUtils.join(validOrderList, ",");
        return OrderReportVO
                .builder()
                .dateList(dataString)
                .validOrderCountList(validOrderString)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(orderCountString)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        String dataString = StringUtils.join(dateList, ",");
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map mapTotal = new HashMap();
            Map mapNew = new HashMap();
            mapTotal.put("begin",localDateTimeBegin);
            mapTotal.put("end",localDateTimeEnd);
            mapNew.put("end",localDateTimeEnd);
            Integer totalUser = userMapper.getCount(mapTotal);
            Integer newUser = userMapper.getCount(mapNew);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        String totalString = StringUtils.join(totalUserList, ",");
        String newString = StringUtils.join(newUserList, ",");
        return UserReportVO.builder().totalUserList(totalString).dateList(dataString).newUserList(newString).build();
    }

    /**
     * 求前十菜品
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime localDateTimeBegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.top10(localDateTimeBegin,localDateTimeEnd);
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber().toString());
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        LocalDate dataBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dataBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        //写入文件
        InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = excel.getSheet("Sheet1");
        XSSFRow row = sheet.getRow(1);
        row.getCell(1).setCellValue("时间： "+ dataBegin +" 至 "+ dateEnd );
        row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());


        for (int i = 0; i < 30; i++) {
            LocalDate date = dataBegin.plusDays(i);
            BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(String.valueOf(date));
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
        }

        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        fileInputStream.close();
        out.close();
        excel.close();
    }
}
